package com.wuji1626.spark.kryo;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.esotericsoftware.kryo.serializers.BeanSerializer;
import org.apache.spark.storage.BufferReleasingInputStream;

import java.io.*;
import java.lang.reflect.Array;
import java.util.ArrayList;

public class KryoTest {

    public static void javaSerial(Serializable s, String filePath) throws IOException {
        ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(filePath)));
        out.writeObject(s);
        out.flush();
        out.close();
    }

    // 序列化对象到 .dat 文件
    public static void kryoSerialize(Object obj, String filePath) {
        try (Output output = new Output(new FileOutputStream(filePath))) {
            Kryo kryo = new Kryo();
            kryo.setReferences(false); // 关闭引用
            kryo.writeObject(output, obj);
        } catch (Exception e) {
            throw new RuntimeException("Serialization failed", e);
        }
    }


    // 从 .dat 文件反序列化对象
    public static <T> T kryoDeserialize(String filePath, Class<T> clazz) {
        try (Input input = new Input(new FileInputStream(filePath))) {
            Kryo kryo = new Kryo();
            kryo.setReferences(false); // 必须与序列化端一致
            return kryo.readObject(input, clazz);
        } catch (Exception e) {
            throw new RuntimeException("Deserialization failed", e);
        }
    }

    public static void main(String[] args) throws IOException {
        User user = new User();
        user.setAge(20);
        user.setName("zhangsan");
        javaSerial(user, "D:/user.dat");
        kryoSerialize(user, "D:/user2.dat");

        user = kryoDeserialize("D:/user2.dat", User.class);
        System.out.println(user.getName());
        System.out.println(user.getAge());

        ArrayList list = new ArrayList();
    }

}
class User implements Serializable {
    private transient String name;
    private int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}